import os
import urllib
import urllib2
import gzip
import StringIO

from bencode import bdecode

class SeedAnalyse:
    def __init__(self):
        pass
      
    
    def analyse(self, info_hash):      
        data = self.__downSeed(info_hash)
        if len(data) <= 0:
            print "not data about the seed"
            return
        btData = bdecode(data)
        return btData


        
    def __downSeed(self, info_hash):  
        data = ""
        data = self.__downSeekByZoink( info_hash)        
        if len(data) == 0:
            data = self.__downSeekByTorcache( info_hash)
        if len(data) == 0:
            data = self.__downSeekBytorrage( info_hash)

        return data      
      

    def __downSeekByUrl(self, url):
        print url
        try:
            f = urllib2.urlopen(url, data=None, timeout=3)
            data = f.read()
            headers = f.info()
        except Exception as err:
            print(err)
            data = ""
        finally:
            if data != "" and('content-encoding' in headers) and   (headers['content-encoding']) == 'gzip':
                    return self.__unGzip(data)
            return data

    def __downSeekByZoink(self, info_hash):
        url =  'http://zoink.it/torrent/' + info_hash + ".torrent"
        return self.__downSeekByUrl(url)
        
    

    def __downSeekByn0808(self, info_hash):
        url =  "http://bt.box.n0808.com/"+ info_hash[0:2] +"/" + info_hash[-2:]+"/"+ info_hash + ".torrent"
        return self.__downSeekByUrl(url)

        
    def __downSeekByVuze(self, info_hash):
        url =  'http://magnet.vuze.com/magnetLookup?hash=' + info_hash
        return self.__downSeekByUrl(url)


    def __downSeekByTorcache(self, info_hash):
        url =  'http://torcache.net/torrent/' + info_hash + ".torrent"
        return self.__downSeekByUrl(url)
        
    def __downSeekBytorrage(self, info_hash):
        url =  'http://torrage.com/torrent/' + info_hash + ".torrent"
        return self.__downSeekByUrl(url)
        
        
    def __unGzip(self, data):
        compressed_file = StringIO.StringIO()
        compressed_file.write(data)
        compressed_file.seek(0)
        decompressed_file = gzip.GzipFile(fileobj = compressed_file, mode = 'rb')
        return decompressed_file.read()

    
"""
s = SeedAnalyse()
seed = s.analyse('640FE84C613C17F663551D218689A64E8AEBEABE')
print "announce:" + seed['announce']
info = seed['info']
print "name:" + str(info['name'])
print "name:" + str(info['name'])
print "name:" + str(info['name'])
print "name:" + str(info['name'])
print "name:" + str(info['name'])
print "name:" + str(info['name'])
"""

    
